import Taro, {Component} from "@tarojs/taro";
import html2canvas from 'html2canvas'
import { QRCode } from 'taro-code'
import {View, Image, Text} from "@tarojs/components";

import {companyName, getRuntime, ServerHost} from '../../utils/common'


import './qrcode.less'

import bg_19 from "../../assets/img/bg_19.jpg";
import bg_18 from "../../assets/img/bg_18.jpg";
import img_11 from "../../assets/img/img_11.png";

// 我的二维码
class Company extends Component {
  constructor(props) {
    super(props)
  }

  state = {
    userInfo: null,
    invitationCode: null,
    shareImgSrc: '',
    isShow: false
  }

  componentWillMount(): void {
    Taro.setNavigationBarTitle({ title:'我的二维码' })
    let userInfo = getRuntime().getUserInfo()
    this.setState({
      userInfo
    })
  }

  componentDidMount(): void {
    //this.getJsApiParam()
  }

  componentDidShow(): void {
    //this.share()
  }

  getInvitationCode(userId: string = '') {
    let len = userId.length
    let res = userId
    if(len<5) { res = new Array(5-len).fill(0).join('')+userId }
    //this.setState({invitationCode: res})
    return res
  }

  handelRouter(url: string = '/pages/index/index'): void {
      getRuntime().navigateTo(url)
  }

  // 配置微信分享
  getJsApiParam = () => {
    let currentUrl = window.location.href
    let apiUrl = `${ServerHost}/api/Account/getWxJsApiParams?curUrl=${currentUrl}`
    Taro.showLoading({title: '加载中...'})
    fetch(apiUrl, {
      method: 'GET',
      mode: "cors",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      credentials: 'same-origin'
    })
      .then(response => {
        Taro.hideLoading()
        return response.json()
      })
      .then(response => {
        let appId = response.appId
        let timestamp = response.timestamp
        let nonceStr = response.nonceStr
        let signature = response.signature
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: appId, // 必填，公众号的唯一标识
          timestamp: timestamp, // 必填，生成签名的时间戳
          nonceStr: nonceStr, // 必填，生成签名的随机串
          signature: signature,// 必填，签名
          // jsApiList: ['updateAppMessageShareData','onMenuShareAppMessage'], // 必填，需要使用的JS接口列表
          jsApiList: 'updateAppMessageShareData,onMenuShareTimeline,onMenuShareAppMessage,onMenuShareQQ,onMenuShareWeibo'.split(',')
        });
      })
      .catch(error => {
        console.log(error)
      })
  }


  html2Canvas = () => {
    let shareContent = document.getElementById('my_my_code');//需要截图的包裹的（原生的）DOM 对象
    let width = shareContent.offsetWidth; //获取dom 宽度
    let height = shareContent.offsetHeight; //获取dom 高度

    let opts = {
      scale: 2, // 添加的scale 参数
      logging: true, //日志开关
      width: width, //dom 原始宽度
      height: height, //dom 原始高度
      backgroundColor: 'transparent',
      useCORS: true,
      allowTaint: true,
      logging: false,
    };
    const that = this;
    Taro.showLoading({ title: '海报生成中...' })
    html2canvas(shareContent, opts).then( canvas => {
      Taro.hideLoading()
      this.setState({ isShow: true })
      let shareImgSrc = canvas.toDataURL("image/jpeg")
      that.setState({ shareImgSrc: shareImgSrc })
    })
  }

  share() {
    // if(!getRuntime().getToken()) { getRuntime().navigateTo('/pages/login/login'); return }
    let { userInfo } = this.state
    let url = `${ServerHost}/m/#/pages/login/registerStepOne?invitationCode=${userInfo.id}`
    let title = `一站式${companyName}代缴服务!`
    let desc = '快来加入我们吧!'
    // let imgUrl = `${ServerHost}/m/logo.png`
    var shareData = {
      title,
      desc,
      imgUrl,
      url,
      link: url
    };
    wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
      wx.onMenuShareTimeline(shareData);
      wx.updateAppMessageShareData(shareData);
      wx.onMenuShareQQ(shareData);
      wx.onMenuShareWeibo(shareData);
    });
    // WxShare(url,item.logo,item.title,partOf(item.content, 30))
  }

  close(e) {
    e.preventDefault()
    e.stopPropagation()
    this.setState({ isShow: false })
  }

  render() {
    let { userInfo,invitationCode,shareImgSrc,isShow } = this.state
    return (
      <View>
        <View className='my-my_code' id='my_my_code' onClick={this.html2Canvas.bind(this)}>
          <View className='my-my_code'>
            <Image src={bg_19} className='bg'/>

            <View className='header'>

              <View className='desc'>
                <Text className='con' >一站式车船税代缴服务</Text>
              </View>
              <View className='title'>邀请好友 一起赚赏金</View>

            </View>
            <View className='main'>
              <Image src={bg_18} className='bg-info' />
              <View className='info'>
                <View className='title'>新用户注册有好礼</View>
                <View className='name'>{userInfo.name}</View>
                <QRCode className='img-code' text={ServerHost+'/m/#/pages/login/registerStepOne?invitationCode='+userInfo.id} size={125}  />
                <View className='code '>邀请码： {this.getInvitationCode(String(userInfo.id))}</View>
              </View>
            </View>
          </View>
        </View>
        {isShow&&
        <View className='share-img' onClick={this.close.bind(this)}>
           <Image className='img img-active' src={shareImgSrc} />
           <View className='tipsText'>长按保存图片、识别二维码</View>
        </View>
        }
      </View>
    )
  }
}

export default Company
